package com.dapeis.api.utils.threadlocal;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ag.utils.NumberUtils;
import com.ag.utils.SpringUtils;
import com.dapeis.domain.User;
import com.dapeis.service.UserService;
/**
 * 预留后期 用户端 App 接口，需要配置拦截器
 * Title:UserThreadLocal.java UserThreadLocal
 * Description:
 * @author yuanyong
 * @date 2017年5月3日 上午9:27:34 
 * Email: hzyuanyong@126.com
 *
 */

public class UserThreadLocal extends ThreadLocal<User> {
	public final Logger logger = LoggerFactory.getLogger(getClass());
	ThreadLocal<Integer> userIdThreadLocal = new ThreadLocal<Integer>();
	
	public UserThreadLocal() {}
	public UserThreadLocal(Integer userId) {}
	
	@Override
	public User get() {
		User user = super.get();
		if (user == null) {
			logger.warn("user is null.");
		}
		return user;
	}
	
	@Override
	protected User initialValue() {
		Integer userId = userIdThreadLocal.get();
		if(NumberUtils.isNotValid(userId)) {
			return null;
		}
		
		UserService userService = SpringUtils.getBean(UserService.class);
		User user = userService.getUserByUserId(userId);
		
		if(user == null) {
			logger.warn("不存在的用户:" + userId);
		}
		
		return user;
	}
	

	@Override
	public void remove() {
		super.remove();
		this.userIdThreadLocal.remove();
	}
	
	public void resetUserId(Integer userId) {
		this.remove();
		this.userIdThreadLocal.set(userId);
	}
}